package com.zsr.example.controller;


import com.alibaba.fastjson.JSONObject;
import com.zsr.example.config.exception.CommonJsonException;
import com.zsr.example.entity.EduSection;
import com.zsr.example.service.EduCourseService;
import com.zsr.example.service.EduSectionService;
import com.zsr.example.util.CommonUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;

/**
 * <p>
 * 课程小节部分 前端控制器
 * </p>
 *
 * @author zsr
 * @since 2021-11-15
 */
@RestController
@RequestMapping("/section")
public class EduSectionController {
    @Autowired
    private EduSectionService eduSectionService;
    @Autowired
    private EduCourseService courseService;

    @PostMapping("save")
    public JSONObject save(
            @RequestBody EduSection videoInfoForm) {
        eduSectionService.save(videoInfoForm);
        //更新课时数
        courseService.updateLessonNum(videoInfoForm.getCourseId(), true);
        return CommonUtil.success();
    }

    @DeleteMapping("{id}")
    public JSONObject removeById(
            @PathVariable String id) {
        EduSection section = eduSectionService.getById(id);
        if (ObjectUtils.isEmpty(section)) throw new CommonJsonException("20001", "小节不存在");
        boolean result = eduSectionService.removeVideoById(section.getId());
        courseService.updateLessonNum(section.getCourseId(), false);
        return result ? CommonUtil.success() : CommonUtil.errorJson();

    }

    @GetMapping("{id}")
    public JSONObject getSectionInfoById(
            @PathVariable String id) {

        EduSection videoInfoForm = eduSectionService.getById(id);
        return CommonUtil.successJson(videoInfoForm);
    }

    @PostMapping("update")
    public JSONObject update(
            @RequestBody EduSection videoInfoForm) {

        eduSectionService.updateById(videoInfoForm);
        return CommonUtil.success();
    }
}

